﻿using System;
using System.Windows.Controls;
using System.Windows.Input;
using MPlayer.Common;

namespace FrontDisplay.Music
{
    /// <summary>
    /// Interaction logic for PlaylistPage.xaml
    /// </summary>
    public partial class PlaylistPage : UserControl
    {
        public MusicPlugin Music { get; private set; }

        public PlaylistPage(MusicPlugin music)
        {
            Music = music;

            InitializeComponent();

            Playlist.ItemsSource = Music.Player.Playlist;

            Music.Player.PlaylistChanged += ((sender, param) => this.InvokedCall(PlaylistChanged));
            Music.Player.CurrentPlayerChanged += (sender => this.InvokedCall(PlayerChanged, sender));
            PlaylistChanged();

            Playlist.SelectionChanged += PlaylistSelectionChanged;
        }

        private void PlayerChanged(IMusicPlayer player)
        {
            if (!IsVisible) return;

            UpdatePlayerInfo();
        }

        private void PlaylistChanged()
        {
            if (!IsVisible) return;
            Playlist.Items.Refresh();
        }

        private void PlaylistSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Playlist.SelectedIndex < 0) return;

            if (Playlist.SelectedIndex != Music.Player.CurrentSongPos)
            {
                Music.Player.Seek(Playlist.SelectedIndex, 0);
            }
        }

        public void UpdatePlayerInfo()
        {
            Playlist.ItemsSource = Music.Player.Playlist;
            Playlist.Items.Refresh();
            PlayerName.Text = Music.Player.Name;
            SelectActiveSong();
        }

        private void SelectActiveSong()
        {
            int pos = Music.Player.CurrentSongPos;
            if (pos < 0) return;
            if (Playlist.Items.Count > pos)
            {
                Playlist.SelectedItem = Playlist.Items[pos];
                Playlist.ScrollIntoView(Playlist.SelectedItem);
            }
        }

        private void PlaylistItemMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.NavigateBack(Animation.Fadeout);
        }

        private void BackButtonMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.NavigateBack(Animation.MoveRight);
        }
    }
}
